﻿@page "/PageShowGrainSize"

@using BootstrapBlazor.Components;
@using System.Collections.Concurrent;
@using System.Collections.Generic;
@using System.Linq;
@using AntDesign.Charts
@using SubstrateHelper.Models;
@using SubstrateHelper.Data;
@inject SubstrateHelperDbContext Db
@inject MessageService MessageService

<AuthorizeView>
    <Authorized>
        <div>
            <div class="m-4">
                <h4 class="text-primary text-center">晶粒大小趋势图</h4>
            </div>
            <Line Data="data" Config="config" @ref="@chart" />

            <div class="m-4">
                <span class="text-primary mb-4">请选择要显示的种类：</span>
                <MultiSelect Items="@Categories" @bind-Value="SelectedCategories" OnSelectedItemsChanged="OnSelectedItemsChanged" />
            </div>
        </div>
    </Authorized>
    <NotAuthorized>
        <div>您未登录！请<a href="Identity/Account/Login">登录</a>后进行操作。</div>
    </NotAuthorized>
</AuthorizeView>


@code{
    List<PSDPoint> data { get; set; }

    List<PSDPoint> AllData { get; set; }
    public IChartComponent chart;


    LineConfig config = new LineConfig()
    {
        
        Title = new AntDesign.Charts.Title()
        {
            Visible = true,
            Text = "晶粒大小趋势图",
            AlignTo = "middle"
        },
        Description = new Description()
        {
            Visible = true,
            Text = "将数据按照某一字段进行分组，用于比对不同类型数据的趋势。",
        },
        Padding = "auto",
        ForceFit = true,
        XField = "date",
        YField = "value",
        YAxis = new ValueAxis()
        {
            Label = new BaseAxisLabel()
            {
                // 数值格式化为千分位
                Visible = true
            },
            TickCount = 30,
            Visible = true,
            Max = 60,
            Min = 0,
            Title = new BaseAxisTitle
            {
                Visible = true,
                Text = "晶粒大小(um)"
            }


        },
        Point = new LineViewConfigPoint()
        {
            Size = 5
        },
        Legend = new Legend()
        {
            Position = "right-top",
            OffsetY = 20,
        },
        SeriesField = "category",@*responsive = true,*@
        Smooth = false
    };

List<SelectedItem> Categories { get; set; }

string SelectedCategories { get; set; }




protected override async Task OnInitializedAsync()
{
    //初始化
    Categories = new List<SelectedItem>();

    AllData = new List<PSDPoint>();

    List<string> _cats = new List<string>();

    //D10
    string[] psdTypes = new string[] { "晶粒大小" };

    Dictionary<string, double> limits = new Dictionary<string, double>();
    foreach (var psdType in psdTypes)
    {
        foreach (var record in Db.Records.Where(x => x.ParameterName == psdType && x.NumberValue != null))
        {
            var lot = Db.Records.Where(x => x.Guid == record.Guid && x.ParameterName == "产出标识").Select(x => x.StringValue).FirstOrDefault();
            if (string.IsNullOrWhiteSpace(lot))
            {
                continue;
            }

            string[] strs = lot.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);


            //出站日期即测试粒度日期
            var chuzhan = Db.Records.Where(x => x.Guid == record.Guid && x.ParameterName == "出站日期" && x.DateTimeValue != null).FirstOrDefault();
            if (chuzhan == null)
            {
                continue;
            }



            double value = record.NumberValue.Value;
            string date = chuzhan.DateTimeValue.Value.ToString("yyyy-MM-dd");


            
            string category = $"{psdType}-{record.ProcessName}-{strs[0]}";

            AllData.Add(new PSDPoint
            {
                value = value,
                date = date,
                category = category
            });
            _cats.Add(category);

            //上限，下限
            var para = Db.Parameters.Where(x => x.ParameterName == psdType && x.ProcessName == record.ProcessName).First();
            if (para.StandardLineBottom != null)//下限
            {
                value = para.StandardLineBottom.Value;
                category = $"下限：{psdType}-{record.ProcessName}-{strs[0]}";
                limits[category] = value;
            }
            if (para.StandardLineTop != null)//上限
            {
                value = para.StandardLineTop.Value;
                category = $"上限：{psdType}-{record.ProcessName}-{strs[0]}";
                limits[category] = value;
            }

        }
    }

    //上下线作为直线
    string dateStart = AllData.Select(x => x.date).Distinct().OrderBy(x => x).FirstOrDefault();
    string dateEnd = AllData.Select(x => x.date).Distinct().OrderByDescending(x => x).FirstOrDefault();
    foreach (var limit in limits)
    {
        AllData.Add(new PSDPoint
        {
            value = limit.Value,
            date = dateStart,
            category = limit.Key
        });
        AllData.Add(new PSDPoint
        {
            value = limit.Value,
            date = dateEnd,
            category = limit.Key
        });
        _cats.Add(limit.Key);
    }


    foreach (var cat in _cats.Distinct().OrderBy(x => x))
    {
        Categories.Add(new SelectedItem(cat, cat));
        SelectedCategories += $"{cat},";
    }

    data = AllData.OrderBy(x => x.date).ToList();



}

async Task OnSelectedItemsChanged(IEnumerable<SelectedItem> selectedItems)
{
    data = new List<PSDPoint>();
    foreach (var sel in selectedItems)
    {
        foreach (var pt in AllData.Where(x => x.category == sel.Value))
        {
            data.Add(pt);
        }
    }
    data = data.OrderBy(x => x.date).ToList();
    chart.ChangeData(data);
}

class PSDPoint
{
    public double value { get; set; }
    public string date { get; set; }
    public string category { get; set; }
}
}
